﻿using System.Collections.Generic;

namespace Firefly.Framework.Collections.Spatial
{
    public class QuadTree<T> : List<T> where T : IQuadTreeNode
    {
        protected List<T> DistanceSortedNodeList { get; private set; }
        protected int MaxNodeDepth { get; set; }
        public float HorizontalScale { get; protected set; }
        public float VerticalScale { get; protected set; }
        public T RootNode { get; protected set; }

        public QuadTree()
        {
            DistanceSortedNodeList = new List<T>();
        }

        public T GetQuadNodeFromPoint(float x, float y)
        {
            return GetQuadNodeFromPoint(x, y, RootNode);
        }

        public T GetQuadNodeFromPoint(float x, float y, T rootNode)
        {
            if (rootNode.Status != NodeStatus.LeafNode && rootNode.NodeDepth < MaxNodeDepth)
            {
                if (x < rootNode.XPosition * HorizontalScale + rootNode.NodeScale * HorizontalScale / 2)
                {
                    if (y < rootNode.YPosition * HorizontalScale + rootNode.NodeScale * HorizontalScale / 2)
                    {
                        return GetQuadNodeFromPoint(x, y, (T)rootNode.LeftUpNode);
                    }
                    else
                    {
                        return GetQuadNodeFromPoint(x, y, (T)rootNode.RightUpNode);
                    }
                }
                else
                {
                    if (y < rootNode.YPosition * HorizontalScale + rootNode.NodeScale * HorizontalScale / 2)
                    {
                        return GetQuadNodeFromPoint(x, y, (T)rootNode.LeftDownNode);
                    }
                    else
                    {
                        return GetQuadNodeFromPoint(x, y, (T)rootNode.RightDownNode);
                    }
                }
            }
            else
            {
                return rootNode;
            }
        }
    }
}
